package com.kssoft.ebd.spider.processor;

import cn.hutool.core.thread.ThreadUtil;
import com.kssoft.ebd.spider.common.CommonUtils;
import com.kssoft.ebd.spider.common.NullCookiesException;
import com.kssoft.ebd.spider.common.PageModelType;
import com.kssoft.ebd.spider.common.config.SpiderConfig;
import com.kssoft.ebd.spider.http.HttpClientUtil;
import org.openqa.selenium.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.io.*;
import java.util.Map;
import java.util.Set;

/**
 * @author liwu
 * @since 2025/6/18
 */
@Component
public class CloseBroadcastProcessor implements PageProcessor {

    @Autowired
    private SpiderConfig spiderConfig;
    private Set<Cookie> closeBroadcastHomeCookies;
    @Autowired
    private HomeProcessor homeProcessor;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final Site SITE = Site.me().setRetryTimes(3).setSleepTime(100).setTimeOut(3000);

    @Override
    public void process(Page page) {

        //判断是否登录主页
        if (page.getHtml().xpath("//*[@id=\"password\"]").match() || page.getRawText().contains("登录") || page.getRawText().contains("login")) {
            toCloseBroadcastHome();
            logger.info("登录关广播成功");
        }

        logger.info("登录关广播cookie 有效");
    }

    @Override
    public Site getSite() {
        try {
            CommonUtils.getCookieToSite(SITE, PageModelType.CloseBroadcast, SpiderConfig.CLOSE_BROADCAST_COOKIE_FILE_PATH);
        } catch (Exception e) {
            toCloseBroadcastHome();
            try {
                CommonUtils.getCookieToSite(SITE, PageModelType.CloseBroadcast, SpiderConfig.CLOSE_BROADCAST_COOKIE_FILE_PATH);
            } catch (Exception ex) {

            }
        }
        return SITE;
    }

    // 模拟点击菜单跳转到关播主页
    public void toCloseBroadcastHome(){
        WebDriver driver  = CommonUtils.webDriverHashMap.get(PageModelType.Home);
        if (driver == null) {
            driver = homeProcessor.getHomeDriver();
        }
        ThreadUtil.sleep(3000);
        logger.info("关始登录关广播"+driver);
        driver.get(spiderConfig.getCloseBroadcastHomePageUrl());
        ThreadUtil.sleep(3000);
        closeBroadcastHomeCookies = driver.manage().getCookies();
        try {
            CommonUtils.saveCloseBroadcastCookies(closeBroadcastHomeCookies);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取关播主页cookie
     * @return
     */
    public Map<String, String> getCloseBroadcastCookies() {
        if(isLogin()){
            try {
                return CommonUtils.getCloseBroadcastCookies();
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            } catch (NullCookiesException e) {
                throw new RuntimeException(e);
            }
        }
        start();
        try {
            return CommonUtils.getCloseBroadcastCookies();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取关播cookie 失败");
            throw new RuntimeException(e);
        }
    }

    private WebDriver start() {

        Map<String, String> closeBroadcastCookies = null;
        try {
            closeBroadcastCookies = CommonUtils.getCloseBroadcastCookies();
        } catch (Exception e) {
            logger.error("获取关播cookie 失败");
        }
        if (closeBroadcastCookies != null) {
//            Spider.create(this).addUrl(spiderConfig.getCloseBroadcastHomePageUrl()).run();
            if(isLogin()){
                return CommonUtils.webDriverHashMap.get(PageModelType.Home);
            }
            // closeBroadcastCookies 失效 先清空  cookie  后
            try {
                CommonUtils.removeCookies(PageModelType.CloseBroadcast);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        Map<String, String> homeCookies = homeProcessor.getHomeCookies();
        if (homeCookies != null) {
            // home cookie 不为空 登录关播页
            //先校验home页cookie是否有效
            if(!homeProcessor.isLogin()){
                logger.error("home页cookie 失效");
                //重新获取home页cookie
                homeProcessor.getHomeCookies();
            }
            toCloseBroadcastHome();
        }


        return CommonUtils.webDriverHashMap.get(PageModelType.Home);
    }

    /**
     *   判断关播主页登录状态 是否有效 然后 判断 home页登录状态 是否有效 以此递归获取home页cookie
     * @return
     */
    public boolean isLogin() {

        Map<String, String> closeBroadcastCookies =   null;
        try {
            closeBroadcastCookies = CommonUtils.getCloseBroadcastCookies();
        } catch (Exception e) {
            logger.error("获取关播页cookie 失败");
        }
        if(closeBroadcastCookies != null){
            try {
                String result = HttpClientUtil.doGet(spiderConfig.getCloseBroadcastHomePageUrl(), null, closeBroadcastCookies, null);
                if(result.contains("登录") || result.contains("password")){
                    logger.error("关播主页登录状态: false");
                    return false;
                }
                logger.info("关播主页登录状态: true");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("获取关播主页cookie 登录状态异常");
                throw new RuntimeException(e);
            }
        }
        logger.error("closeBroadcastCookies = null ,关播主页登录状态: false");
        return false;
    }

}
